package com.txtsqlclient.dataaccess.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.txtsqlclient.domain.ConfigurationException;
import com.txtsqlclient.domain.DataSourceType;

/**
 * This class is required to get DataSourceTypes.
 * 
 * @author spadda
 */
public class DataSourceTypeDAO {

	private static DataSourceTypeDAO instance;

	public static final String SC_HOME = System.getProperty("sc.home");

	/** Name of the local file containing the DataSourceTypes. */
	private static final String TYPES_FILE_NAME = "data-source-types.csv";

	private static Log LOGGER = LogFactory.getLog(DataSourceTypeDAO.class);

	protected DataSourceTypeDAO() {
		// empty constructor to enforce access restrictions.
	}

	public static DataSourceTypeDAO getInstance() {
		if (instance == null) {
			LOGGER
					.debug("Factory instance does not exist. Creating a new instance.");
			instance = new DataSourceTypeDAO();
		}
		return instance;
	}

	/**
	 * This method is required to get all Data Source Types added by the user in
	 * the settings file.
	 * 
	 * @return
	 * @throws FileException
	 */
	public List<DataSourceType> getDataSourceTypes()
			throws ConfigurationException {
		List<DataSourceType> types = new LinkedList<DataSourceType>();
		File typesFile = new File(SC_HOME + "/" + TYPES_FILE_NAME);
		String ln = null;
		String[] fields = null;
		DataSourceType type = null;
		try {
			BufferedReader rd = new BufferedReader(new FileReader(typesFile));
			while ((ln = rd.readLine()) != null) {
				ln = ln.trim();
				// Ignore empty lines and commented lines.
				if (ln.length() == 0 || ln.startsWith("#")) {
					LOGGER
							.debug("Ignoring line from the properties file:"
									+ ln);
					continue;
				}
				fields = ln.split(",");
				if (fields.length == 5) {
					type = new DataSourceType(fields[0].trim(), fields[1]
							.trim(), fields[2].trim(), fields[3].trim(),
							new Boolean(fields[4].trim()));
					types.add(type);
				} else {
					LOGGER
							.info("Invalid Data Source Type entry: "
									+ ln
									+ ". Each entry should have 5 comma-separated fields.");
				}
			}
			rd.close();
		} catch (FileNotFoundException e) {
			throw new ConfigurationException("The Data Source Types file: "
					+ TYPES_FILE_NAME + " is not present.", e);
		} catch (IOException e) {
			throw new ConfigurationException(
					"There is a problem reading the Data Source Types file: "
							+ TYPES_FILE_NAME, e);
		}
		return types;
	}
}
